<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <title>Map</title>
  <script
          type="text/javascript"
          src="http://api.tianditu.gov.cn/api?v=4.0&tk=c2325194078734ce4f8914e44b3bec46"
  ></script>
  <script src="http://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
  <script src="{{ url_for('static',filename='vue/vue2.6.js') }}"></script>
  <script src="{{ url_for('static',filename='elementUi/elementUi.js') }}"></script>
  <link
          rel="stylesheet"
          href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"
  />
  <link rel="stylesheet" href="{{ url_for('static',filename='bootstrap/bootstrap@4.6_min.css') }}"/>
</head>
<body onLoad="onLoad()" >
<div id="app">
  <!-- <div id="mapDiv" ></div> -->
  <!-- @click="rectClick(event)" -->
  <nav class="navbar navbar-expand-lg navbar-light bg-light" style="padding: 0 75px;">
    <a class="navbar-brand" href="#">宅基地违占识别系统</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item active">
          <a class="nav-link" href="#">首页<span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">刷新</a>
        </li>
      </ul>
    </div>
  </nav>

  <div class="loading">


  </div>

  <el-container
          v-loading="loading"
          element-loading-text="正在预测......."
          element-loading-background="rgba(0, 0, 0, 0.4)"
          class="container"
  >
    <el-container>
      <el-main class="main">
        <div id="mapDiv" @click="rectClick"></div>
      </el-main>
      <el-aside id="el_aside">
        <hr>
        <!-- 上传文件 -->
        <el-button type="text" @click="dialogVisibleHelp = true" class="help_css">帮助</el-button>
        <el-dialog
                title="提示"
                :visible.sync="dialogVisibleHelp"
                width="40%"
        >
          <span>第一步上传包含准确数据的json文件，第二步打开截图开关，将目标建筑移动至左上角，单击目标建筑截图，第三步截图确认并选择目标建筑物，最后提交</span>
          <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisibleHelp = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisibleHelp = false">确 定</el-button>
  </span>
        </el-dialog>
        <div class="testword">第一步:上传文件</div>

        <div class="putfile">
          <el-upload
                  class="upload-demo"
                  ref="dataFormFile"
                  accept=".json"
                  :multiple="false"
                  :limit="1"
                  :action="upload_file_url"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :on-success="putsucess"
                  :on-error="puterr"
                  :file-list="fileList"
                  :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>

            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传json文件，且不超过500kb</div>
          </el-upload>
          {{ fileList }}
        </div>
        <div class="testword" style="margin-top: 37px;">第二步:打开截图开关</div>
        <div class="jtkg">
          截图开关：
          <el-switch
                  v-model="switchvalue"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
          </el-switch>
        </div>
        {#弹出截图#}
        <div class="tangc" v-show="jtdialogVisible">
          <el-image
                  style="width: 180px; height: 180px"
                  :src="preurl"
                  :preview-src-list="[preurl]"
                  class="tcimg"
          >
          </el-image>

          <span></span>
          <span slot="footer" class="dialog-footer">
        <el-button @click="jtdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="cloimg()">确 定</el-button
        >
      </span>
        </div>
        <div class="tangc" v-show="selectedIndex!=-1">
          <img :src="'data:image/gif;base64,'+imgsrc2[selectedIndex]" alt="" srcset="" class="tcimg">
          <span slot="footer" class="dialog-footer">
        <el-button @click="selectedIndex=-1">取 消</el-button>
        <el-button type="primary" @click="selectTwice()"
        >重新选择</el-button
        >
      </span>
          <el-button type="primary" class="tj" @click="getxsd()">提交</el-button>
          <div class="xsd">相似度是：{[xsd]}</div>
        </div>

      </el-aside>
    </el-container>
  </el-container>


  {#  弹出返回后的图片#}
  <el-dialog
          title="选择一张图片"
          :visible.sync="dialogVisible"
          {#  width="30%"#}
  >
    <div class="tc-wrap" v-if="imgsrc2">
      <div class="img-box">
        <img :src="'data:image/gif;base64,'+yuantu" alt=""/>
        <button class="btn">原图</button>
      </div>

      <div v-for="(item,index) in imgsrc2" class="img-box">
        <img :src="'data:image/gif;base64,'+item" alt=""/>
        <button class="btn" @click="selectingImg=index">选择</button>
      </div>
      {# <div class="xsd">相似度是：${xsd}</div>#}
    </div>
    <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="selectImgToXsd">确 定</el-button>
  </span>
  </el-dialog>
  <!-- 弹出的图片 -->

  <!-- <div class="img">
    <img :src="imgbs64src" alt="" srcset="" >
    <button onclick="xsd()">
      相似度-----------------------------------
    </button>
  </div> -->
</div>
</body>
<script>
    var map;

    function onLoad() {
        map = new T.Map("mapDiv", {
            projection: "EPSG:4326",
        });
        console.log('map====', map);
        map.centerAndZoom(new T.LngLat(120.5629, 27.526106), 12);
        map.setMapType(window.TMAP_SATELLITE_MAP);
        var scaleCtrl = new T.Control.Scale("T_ANCHOR_BOTTOM_LEFT");
        map.addControl(scaleCtrl); //添加比例尺控件
        //去除logo
        document.getElementsByClassName(
            "tdt-control-copyright tdt-control"
        )[0].style.display = "none";
        this.map = map;
    };
    // 1.x
    Vue.config.delimiters = ['{[', ']}']
    new Vue({
        delimiters: ['{[', ']}'],
        el: "#app",
        data() {
            return {
                selectingImg: 0,//正在选择的图片
                selectedIndex: -1,//已经选择
                switchvalue: false,//截图开关
                fileList: undefined,

                map: undefined,
                zoom: 12,
                imgsrc: [],
                imgsrc2: [],
                yuantu: '',
                position: {
                    x: 0,
                    y: 0,
                    lng: 0,
                    lat: 0,
                },
                is_cut: true,
                // 显示loading
                loading: false,
                imgbs64src: '',
                dialogVisible: false,
                jtdialogVisible: false,
                xsd: 0,
                upload_file_url: "http://192.168.43.41:5000/upJsonFile",
                preurl: '',
                dialogVisibleHelp: false,
            };
        },
        methods: {
            selectTwice() {
                this.dialogVisible = true;
            },
            selectImgToXsd() {
                console.log('this.selectingImg', this.selectingImg)
                this.selectedIndex = this.selectingImg;
                console.log('selectedIndex====', this.selectedIndex);
                this.dialogVisible = false;

            },
            getxsd() {
                var request = new XMLHttpRequest();
                var url = "http://192.168.43.41:5000/Compare";
                request.open("POST", url);
                request.setRequestHeader("content-type", "application/json"); //先open再设置请求头
                var obj = {
                    index: this.selectedIndex + 1,
                    lnglat: [this.position.lng, this.position.lat],
                };
                console.log(obj);
                var that = this;
                request.onreadystatechange = function () {
                    if (request.readyState == 4) {
                        console.log("request.status===", request.status);
                        if (request.status == 200) {
                            // console.log(this);
                            that.objt1 = request.responseText;
                            that.objt1 = JSON.parse(that.objt1);
                            that.xsd = that.objt1.Same;

                            {#alert('相似度是'+that.xsd);#}
                            // console.log(typeof(that.objt1));
                            console.log("上传成功2", that.xsd);
                        } else {
                            console.log(
                                "相似度上传失败,检查上传地址是否正确",
                                request.responseText
                            );
                        }
                    }
                };

                obj = JSON.stringify(obj);
                request.send(obj);
            },
            //上传文件
            submitUpload() {
                //开始上传
                console.log('上传完毕');
                this.$refs.dataFormFile.submit()
            },
            puterr(response, file, fileList) {
                console.log('response, file, fileList', response, file, fileList);
            },
            putsucess(res) {
                //获取回传的JSON后，赋值
                //创建面对象
                var tmp = res.coordinates[0]
                var points = []
                for (i = 0; i < tmp.length; i++) {
                    points.push(new T.LngLat(tmp[i][0], tmp[i][1]))
                }
                var polygon = new T.Polygon(points, {
                    color: "red", weight: 3, opacity: 0.5, fillColor: "#FFFF", fillOpacity: 0.5
                });
                //向地图上添加面
                map.clearOverLays();
                //同时将中心移动
                console.log("移动")
                map.setZoom(20);
                map.panTo(points[0])
                map.addOverLay(polygon);
                console.log(res);
            },
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePreview(file) {
                console.log(file);
            },
            getLngLat(lnglat) {
                this.position.lng = lnglat.lng.toFixed(6);
                this.position.lat = lnglat.lat.toFixed(6);
                //map.panTo(lnglat);
                // 选择是否清除全部覆盖物，添加标记
                var marker = new T.Marker(lnglat);
                map.addOverLay(marker);
                console.log('获得金纬度===', this.position.lng)
            },
            rectClick(event) {
                if (!this.switchvalue) return;
                console.log('获取鼠标点击的位置和经纬度mapevent', event);
                //获取鼠标点击的位置和经纬度
                var config = {
                    callback: this.getLngLat,
                };
                pickup = new T.CoordinatePickup(map, config);
                pickup.addEvent();
                //获取相对于当前所指向对象的位置坐标
                // this.position.x = event.offsetX;
                this.position.y = event.offsetY;
                console.log("this.position===", this.position);
                point = new T.LngLat(0, 0);
                if (this.is_cut) {
                    console.log("start cut");
                    var that = this;
                    setTimeout(function () {
                        that.screenCut();
                    }, 1000);
                }
            },
            screenCut() {
                map.clearOverLays();
                const targetDom = document.querySelector("#mapDiv"); // 获取要截图的元素
                //html2canvas 截图
                html2canvas(targetDom, {
                    useCORS: true,
                    timeout: 500,
                }).then((canvas) => {
                    this.printClip(canvas, 512, 512);
                    let dataURL = canvas.toDataURL("image/png", 1);
                    console.log(dataURL)
                    // 没截好的
                    //  this.downloadImage(dataURL)
                });
            },
            downloadImage(url) {
                // 如果是在网页中可以直接创建一个 a 标签直接下载
                let a = document.createElement("a");
                a.href = url;
                a.download = "天地图截图2";
                a.click();
            },
            printClip(canvas, capture_width, capture_height) {
                var clipCanvas = document.createElement("canvas");
                clipCanvas.width = capture_width;
                clipCanvas.height = capture_height;
                // 截取
                capture_x = this.position.x - capture_width; //这里需要调整去除白边
                capture_y = this.position.y - capture_height;
                if (capture_x < 0) {
                    capture_x = 0;
                }
                if (capture_y < 0) {
                    capture_y = 0;
                }
                clipCanvas
                    .getContext("2d")
                    .drawImage(
                        canvas,
                        capture_x,
                        capture_y,
                        capture_width,
                        capture_height,
                        0,
                        0,
                        capture_width,
                        capture_height
                    );
                //保存
                var clipImgBase64 = clipCanvas.toDataURL("image/png", 1);

                // 弹出出截图
                this.preurl = clipImgBase64;
                this.imgbs64src = clipImgBase64;
                this.jtdialogVisible = true;
            },
            cloimg(res) {
                {#this.jtdialogVisible = false;#}
                console.log('弹窗的返回数据===', res);
                this.loading = true;

                var $Blob = this.getBlobBydataURI(this.imgbs64src, "image/jpeg");
                var formData = new FormData();
                formData.append("file", $Blob, "avatar.jpg");
                // console.log('clipImgBase64',clipImgBase64)
                // 组建XMLHttpRequest 上传文件
                var request = new XMLHttpRequest();
                // 上传连接地址
                //request.open("POST",'http://127.0.0.1:5000/upLoadFile');
                request.open("POST", "http://192.168.43.41:5000/perdictImg");
                //request.open("POST", "http://10.0.0.190:5000/perdictImg");

                // return new Promise((resolve, reject) => {
                let that = this;
                request.onreadystatechange = function () {
                    if (request.readyState == 4) {
                        console.log("request.status===", request.status);

                        if (request.status == 200) {
                            console.log("上传成功", request.responseText);
                            console.log(typeof request.responseText);
                            // imgsrc = request.responseText;
                            that.imgsrc = JSON.parse(request.responseText).perdictImgList;
                            console.log("imgsrc===", "data:image/gif;base64," + that.imgsrc);
                            // console.log('imgsrc[0]',imgsrc[0]);
                            console.log(typeof that.imgsrc);
                            // 跳转
                            that.loading = false;
                            that.dialogVisible = true;
                            that.yuantu = that.imgsrc.shift();
                            that.imgsrc2 = that.imgsrc;
                            {#window.location.href="Result?"+that.imgsrc+'?'+that.position.lng+'?'+that.position.lat;#}

                            //location.href="http://127.0.0.1:5000/upLoadFile"
                        } else {
                            console.log(
                                "上传失败,检查上传地址是否正确",
                                request.responseText
                            );
                            that.$message.error('运行计算出错！');
                            that.loading = false;
                        }
                    }
                };
                // })
                request.send(formData);
            },
            getBlobBydataURI(dataURI, type) {
                var binary = atob(dataURI.split(",")[1]);
                var array = [];
                for (var i = 0; i < binary.length; i++) {
                    array.push(binary.charCodeAt(i));
                }
                return new Blob([new Uint8Array(array)], {type: type});
            },
        },
    });
</script>


<style lang="less">
    .help_css {
        position: absolute;
        left: 19px;
        top: 32px;
    }

    .testword {
        font-size: 14px;
        text-align: left;
        padding: 10px;
        margin-top: 49px;
    }

    .xsd {
        margin-top: 30px;
    }

    .tj {
        margin-top: 30px;
    }

    .test {
    }

    /* 上传文件的 */
    .putfile {

    }

    /* 截图开关的样式 */
    .jtkg {
        font-size: 18px;

    }

    .container {
        height: 100%;
    }

    .main {
        /* height: 600px; */
        margin-top: 20px;
        height: 90%;
        width: 100%;
    }

    #mapDiv {
        height: 100%;
        width: 100%;
        outline: none;
    }

    #app .el_header {
        color: red;
        height: 40px !important;
        background-color: #b3c0d1;
        color: #333;
        text-align: center;
        line-height: 40px;
    }

    #el_aside {
        width: 200px !important;
        background-color: #d3dce6;
        color: #333;
        text-align: center;
        position: relative;
        overflow-y: scroll;
        height: 100vh;
        /* line-height: 200px; */
    }

    .smallimg {
        height: 105vh;
        overflow: scroll;
    }


    .tc-wrap {

        display: flex;
        flex-wrap: wrap;
        width: 700px;
        height: 442px;
        overflow-y: scroll
    }

    .el-main {
        background-color: #e9eef3;
        color: #333;
        text-align: center;
        /* line-height: 160px; */
    }

    body > .el-container {
        margin-bottom: 40px;
    }


    .tcimg {
        width: 182px;
        height: 182px;
    }

    .img img {
        width: 182px;
        height: 182px;
    }

    .tangc {
        margin-top: 40px;
    }


    .xsd {
        margin-left: 24px;
        font-size: 16px;

    }

    #app {
        /* width: 100%; */
        margin: 0px 42px;
    }

    .wrap {
        display: flex;
        flex-wrap: wrap;
        border-bottom: 1px solid #ebeef5;
    }

    .img-box {
        margin: 6px;
        text-align: center;
        /* border: dashed 1px rgb(179, 191, 191); */
        border-bottom: 1px solid #ddd;
        padding: 10px;
        border-radius: 3px;
        height: 210px;
    }

    .img-box:hover {
        background-color: #e2eef9;
        /* border-bottom: 1px solid #ddd; */
    }

    .img-box img {
        display: block;
        width: 150px;
        height: 150px;
        border-radius: 3px;
    }

    .btn:hover {
        color: #409eff;
        border-color: #c6e2ff;
        background-color: #ecf5ff;
    }

    .btn {
        display: inline-block;
        line-height: 1;
        white-space: nowrap;
        cursor: pointer;
        background: #fff;
        border: 1px solid #dcdfe6;
        color: #606266;
        -webkit-appearance: none;
        text-align: center;
        box-sizing: border-box;
        outline: 0;
        margin-top: 5px;
        transition: .1s;
        font-weight: 500;
        padding: 12px 20px;
        font-size: 14px;
        border-radius: 4px;
    }
    body {
        overflow-x: hidden;
        overflow-y: hidden;
    }

</style>
</html>
